<template>
  <a-card :bordered="false">
    <!-- 快捷查询 -->
    <div class="c-container">
      <a-row>
        <a-col :xl="8" :lg="8" :md="8" :sm="24" style="height: 60px">
          <img src="@/assets/crm/business.png" />
          <span class="title actived'" style="font-weight: 700; font-size: 16px">商机管理</span>
        </a-col>
        <a-col :xl="14" :lg="12" :md="12" :sm="24">
          <div class="searchBox">
            <a-input-search
              placeholder="请输入商机名称"
              enter-button="搜索"
              size="default"
              v-model="queryParam.businessName"
              @keyup.enter.native="searchQuery"
              @search="searchQuery"
            />
          </div>
        </a-col>
        <a-col :xl="2" :lg="4" :md="4" :sm="24">
          <a-button @click="handleAdd" style="margin-top: 15px" class="xr-btn--orange" type="primary" icon="plus"
            >新增</a-button
          >
        </a-col>
      </a-row>
    </div>

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <oufu-scene-slider
        ref="oufuSlider"
        :title="sliderTitle"
        :sceneType="sceneType"
        :columns="columns"
      ></oufu-scene-slider>
      <div>
        <span style="margin: 0 5px">产品品类： </span>
        <j-dict-select-tag
          style="width: 200px"
          placeholder="请选择产品品类"
          v-model="queryParam.productCategory"
          :triggerChange="true"
          @change="productCateChange"
          dictCode="DataDictionary,description,dictionaryId, dictionaryTypeId =PRODUCT_CATEGORY"
        />
         <span style="margin: 0 5px">商机阶段： </span>
          <j-dict-select-tag
          style="width: 200px"
          placeholder="请选择商机阶段："
          v-model="queryParam.statusId"
          :triggerChange="true"
          @change="StatusIdChange"
          dictCode="DataDictionary,description,dictionaryCode, dictionaryTypeId =BUSINESS_STATUS_ID"
        />
      </div>
      <!--
      <a-upload
        name="file"
        :showUploadList="false"
        :multiple="false"
        :headers="tokenHeader"
        :action="importExcelUrl"
        @change="handleImportExcel"
      >
        <a-button type="primary" icon="import">导入</a-button>
      </a-upload>
      -->

      <a-dropdown v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay">
          <a-menu-item key="1" @click="batchDel"><a-icon type="delete" />删除</a-menu-item>
          <a-menu-item key="2" @click="handleExportXls('商机表')"><a-icon type="download" />导出</a-menu-item>
        </a-menu>
        <a-button> 批量操作 <a-icon type="down" /></a-button>
      </a-dropdown>
    </div>

    <!-- table区域-begin -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择
        <a style="font-weight: 600">{{ selectedRowKeys.length }}</a
        >项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>

      <a-table
        ref="table"
        size="middle"
        bordered
        rowKey="id"
        :rowClassName="rowClassName"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :scroll="{ x: 1200 }"
        :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
        class="j-table-force-nowrap"
        @change="handleTableChange"
      >
        <template slot="businessName" slot-scope="text, record">
          <a-tooltip placement="top">
            <template slot="title">
              <span>{{ record.businessName }}</span>
            </template>
            <span class="ellipsis"
              >
              <a v-if="record.infoStatusId === '1'">{{ record.businessName }}</a>
              <a v-else @click="() => handleViewDrawer(record)">{{ record.businessName }}</a>
              </span
            >
          </a-tooltip>
        </template>
        <template slot="htmlSlot" slot-scope="text">
          <div v-html="text"></div>
        </template>
        <template slot="imgSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px; font-style: italic">无图片</span>
          <img
            v-else
            :src="getImgView(text)"
            height="25px"
            alt=""
            style="max-width: 80px; font-size: 12px; font-style: italic"
          />
        </template>
        <template slot="fileSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px; font-style: italic">无文件</span>
          <a-button v-else :ghost="true" type="primary" icon="download" size="small" @click="uploadFile(text)">
            下载
          </a-button>
        </template>
        <span slot="followup" slot-scope="followup, record"> {{ record.followup }}% </span>
        <span slot="action" slot-scope="text, record">
          <a-button v-if="record.infoStatusId == '1'" @click="handleAcitve(record)">申请激活</a-button>
          <a-button v-if="record.infoStatusId == '2'" disabled="true">申请激活中</a-button>
          <a-button  v-if="(record.infoStatusId !== '1') && (record.infoStatusId !== '2') && (record.getNotUpdate == 'Y') && (record.statusId !='6' && record.statusId !='7')" @click="setNotUpdateTime(record.id)">无更新</a-button>
          <a-divider v-if="(record.infoStatusId == '1') || ((record.infoStatusId !== '1') && (record.getNotUpdate == 'Y') && (record.statusId !='6' && record.statusId !='7'))" type="vertical" />
          <a-tooltip placement="top">
            <template slot="title">
              <span v-if="record.star == 0">添加关注</span>
              <span v-else>取消关注</span>
            </template>
            <i
              @click="toggleStar(record)"
              :style="
                record.star == 0 ? { color: '#d9d9d9', cursor: 'pointer' } : { color: '#fac23d', cursor: 'pointer' }
              "
              class="wk wk-focus-on"
            ></i>
          </a-tooltip>
        </span>
      </a-table>
    </div>

    <crmBusiness-modal
      ref="modalForm"
      @ok="modalFormOk"
      @reload="reload"
      @loadDetailInfo="handleViewDrawer"
    ></crmBusiness-modal>
    <crmBusiness-modal-drawer
      ref="modalFormDrawer"
      @handleDelete="handleDelete"
      @handleEdit="handleEdit"
    ></crmBusiness-modal-drawer>
  </a-card>
</template>

<script>
import '@/assets/less/TableExpand.less'
import { mixinDevice } from '@/utils/mixin'
import { MonthsBetw, getNowDate, compareDate ,getDaysBetween} from '@/utils/util'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import CrmBusinessModal from './modules/CrmBusinessModal'
import CrmBusinessModalDrawer from './modules/CrmBusinessModal__Style#Drawer'
import moment from 'moment'
import OufuSceneSlider from '@/components/jeecg/OufuSceneSlider.vue'
import JSearchSelectTag from '@/components/dict/JSearchSelectTag'
import { httpAction, getAction } from '@/api/manage'
import { mapGetters } from 'vuex'

function number_format(number, decimals, dec_point, thousands_sep) {
  /*
   * 参数说明：
   * number：要格式化的数字
   * decimals：保留几位小数
   * dec_point：小数点符号
   * thousands_sep：千分位符号
   * */
  number = (number + '').replace(/[^0-9+-Ee.]/g, '')
  var n = !isFinite(+number) ? 0 : +number,
    prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
    sep = typeof thousands_sep === 'undefined' ? ',' : thousands_sep,
    dec = typeof dec_point === 'undefined' ? '.' : dec_point,
    s = '',
    toFixedFix = function (n, prec) {
      var k = Math.pow(10, prec)
      return '' + Math.ceil(n * k) / k
    }

  s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.')
  var re = /(-?\d+)(\d{3})/
  while (re.test(s[0])) {
    s[0] = s[0].replace(re, '$1' + sep + '$2')
  }

  if ((s[1] || '').length < prec) {
    s[1] = s[1] || ''
    s[1] += new Array(prec - s[1].length + 1).join('0')
  }
  return s.join(dec)
}
export default {
  name: 'CrmBusinessList',
  mixins: [JeecgListMixin, mixinDevice],
  components: {
    CrmBusinessModal,
    OufuSceneSlider,
    CrmBusinessModalDrawer,
    moment,
    JSearchSelectTag,
  },
  data() {
    return {
      sliderTitle: '团队',
      description: '商机表管理页面',
      //场景定义开始
      sceneType: 'CrmBusiness',
      //场景定义结束
      queryParam: {
        ownerUserId: this.userInfo().userLoginId,
        productCategory: '',
        infoStatusId: '',
      },
      isorter: {
        column: 'updateTime',
        order: 'desc',
      },
      // 表头
      columns: [
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function (t, r, index) {
            return parseInt(index) + 1
          },
          fixed: 'left',
        },
        // {
        //   title: '客户经理',
        //   align: 'center',
        //   sorter: (a, b) => a.ownerUserId_dictText - b.ownerUserId_dictText,
        //   dataIndex: 'ownerUserId_dictText',
        //   width: 150,
        //   fixed: 'left',
        //   ellipsis: true,
        // },
        // {
        //   title: 'BU',
        //   width: 200,
        //   ellipsis: true,
        //   align: 'center',
        //   dataIndex: 'ownerUserId_bu',
        // },
        // {
        //   title: '商机名称',
        //   align: 'center',
        //   width: 200,
        //   sorter: (a, b) => a.businessName - b.businessName,
        //   dataIndex: 'businessName',
        //   scopedSlots: { customRender: 'businessName' },
        // },
        // {
        //   title: '客户名称',
        //   width: 220,
        //   align: 'center',
        //   sorter: (a, b) => a.customerId_dictText - b.customerId_dictText,
        //   dataIndex: 'customerId_dictText',
        //   ellipsis: true,
        // },

        // {
        //   title: '销售阶段',
        //   align: 'center',
        //   sorter: (a, b) => a.statusId_dictText - b.statusId_dictText,
        //   dataIndex: 'statusId_dictText',
        //   width: 150,
        // },
        // {
        //   title: '成交概率',
        //   align: 'center',
        //   sorter: (a, b) => a.followup - b.followup,
        //   dataIndex: 'followup',
        //   width: 150,
        //   scopedSlots: { customRender: 'followup' },
        // },
        // {
        //   title: '备注',
        //   align: 'center',
        //   sorter: (a, b) => a.remark - b.remark,
        //   dataIndex: 'remark',
        //   ellipsis: true,
        // },

        // {
        //   title: '创建时间',
        //   align: 'center',
        //   sorter: (a, b) => a.createTime - b.createTime,
        //   dataIndex: 'createTime',
        //   width: 150,
        // },
        {
          title: '商机名称',
          align: 'center',
          width: 200,
          sorter: (a, b) => a.businessName - b.businessName,
          dataIndex: 'businessName',
          scopedSlots: { customRender: 'businessName' },
          fixed: 'left',
        },
        {
          title: '客户名称',
          width: 220,
          align: 'center',
          sorter: (a, b) => a.customerId_dictText - b.customerId_dictText,
          dataIndex: 'customerId_dictText',
          ellipsis: true,
        },
        {
          title: '商机状态',
          width: 200,
          ellipsis: true,
          align: 'center',
          dataIndex: 'infoStatusId_dictText',
        },
        {
          title: '客户经理',
          align: 'center',
          sorter: (a, b) => a.ownerUserId_dictText - b.ownerUserId_dictText,
          dataIndex: 'ownerUserId_dictText',
          width: 150,
          ellipsis: true,
        },
        {
          title: '商机类型',
          width: 200,
          ellipsis: true,
          align: 'center',
          dataIndex: 'typeId_dictText',
        },
        {
          title: '商机金额',
          width: 200,
          ellipsis: true,
          align: 'center',
          dataIndex: 'estimatedSalesAmount',
        },
        {
          title: '仓库',
          width: 200,
          ellipsis: true,
          align: 'center',
          dataIndex: 'warehouseName',
        },
        {
          title: '冷冻',
          width: 200,
          ellipsis: true,
          align: 'center',
          dataIndex: 'estimatedFreeze',
          customRender: function (t, r, index) {
            return number_format(t, 0, '.', ',')
          },
        },
        {
          title: '冷藏',
          width: 200,
          ellipsis: true,
          align: 'center',
          dataIndex: 'estimatedRefrigerate',
          customRender: function (t, r, index) {
            return number_format(t, 0, '.', ',')
          },
        },
        {
          title: '恒温',
          width: 200,
          ellipsis: true,
          align: 'center',
          dataIndex: 'estimatedConstant',
          customRender: function (t, r, index) {
            return number_format(t, 0, '.', ',')
          },
        },
        {
          title: '常温',
          width: 200,
          ellipsis: true,
          align: 'center',
          dataIndex: 'estimatedNormal',
          customRender: function (t, r, index) {
            return number_format(t, 0, '.', ',')
          },
        },
        {
          title: '商机阶段',
          align: 'center',
          sorter: (a, b) => a.statusId_dictText - b.statusId_dictText,
          dataIndex: 'statusId_dictText',
          width: 150,
        },
        {
          title: '更新时间',
          align: 'center',
          sorter: (a, b) => a.updateTime - b.updateTime,
          dataIndex: 'updateTime',
          width: 200,
        },
        {
          title: '操作',
          width: 175,
          dataIndex: 'action',
          align: 'center',
          scopedSlots: { customRender: 'action' },
          fixed: 'right',
        },
      ],
      url: {
        list: '/online/api/pagingCrmBusiness',
        delete: '/online/api/deleteCrmBusiness',
        deleteBatch: '/online/api/deleteCrmBusinessBatch',
        exportXlsUrl: '/online/api/exportCrmBusinessXls',
        importExcelUrl: '/online/api/importCrmBusinessExcel',
        sceneList: '/online/api/pagingCrmScene',
        createCrmStar: '/online/api/createCrmStar',
        setBusinessLastRemindTime: '/online/api/setBusinessLastRemindTime',
        setCrmBusinessStatus: '/online/api/setCrmBusinessStatus',
      },
      dictOptions: {},
    }
  },
  computed: {
    importExcelUrl: function () {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    },
  },
  methods: {
    getNowDate() {
      var date = new Date()
      let year = date.getFullYear() //获取完整的年份(4位)
      let month = date.getMonth() + 1 //获取当前月份(0-11,0代表1月)
      let day = date.getDate() //获取当前日(1-31)
      if (month < 10) {
        month = '0' + month
      }
      if (day < 10) {
        day = '0' + day
      }
      return year + '-' + month + '-' + day
    },
    rowClassName(record, index) {
      if (record.infoStatusId == '1' || record.infoStatusId == '2') {
        return 'table-color-gray'
      }
      // if(getDaysBetween(record.updateTime.substr(0,10),this.getNowDate()) <= 7){
      //   return 'table-color-green'
      // }
      if(getDaysBetween(record.createTime.substr(0,10),this.getNowDate()) < 30){
        return 'table-icon-new'
      }
      
    },
    ...mapGetters(['userInfo']),
    initDictConfig() {
      const that = this
      this.$bus.on('superParam', function (param) {
        this.queryParam
        if (param.type == 1) {
          that.superQueryParams = ''
          that.superQueryFlag = false
          if (param.data != 0) {
            that.queryParam.ownerUserIdList = param.data
            that.loadData(1)
          } else {
            delete that.queryParam.ownerUserIdList
            that.loadData(1)
          }
        }
        if (param.type == 2) {
          //高级查询方法
          if (!param.data) {
            that.superQueryParams = ''
            that.superQueryFlag = false
          } else {
            that.superQueryFlag = true
            that.superQueryParams = JSON.stringify(param.data)
          }
          that.loadData(1)
        }
      })
    },
    toggleStar(data) {
      this.loading = true
      getAction(this.url.createCrmStar, { id: data.id, crmType: 'business' })
        .then(() => {
          this.loading = false
          this.$message.success(data.star > 0 ? '取消关注成功' : '关注成功')
          data.star = data.star > 0 ? 0 : 1
        })
        .catch(() => {
          this.loading = false
        })
    },
    reload(e) {
      this.$refs.modalFormDrawer.edit(e)
    },
    productCateChange(e) {
      this.queryParam.productCategory = e
      this.loadData()
    },
    StatusIdChange(e) {
      this.queryParam.statusId = e
      this.loadData()
    },
    setNotUpdateTime(id) {
      getAction(this.url.setBusinessLastRemindTime, { id: id }).then((res) => {
        if (res.success) {
          this.$message.success('设置不更新成功！')
          this.loadData()
        }
      })
    },
    handleAcitve(data) {
      this.loading = true
      getAction(this.url.setCrmBusinessStatus, { id: data.id, infoStatusId: '2' })
        .then((res) => {
          if (res.success) {
            this.loading = false
            this.$message.success('正在激活中!')
          }
        })
        .catch(() => {
          this.loading = false
        })
    },
  },
}
</script>
<style scoped>
@import '~@assets/less/common.less';
@import '~@assets/less/pageHead.css';
</style>
<style lang="less" scoped>
/deep/ .ant-input-search-button{
  background-color:#168a40;
  border-color:#168a40;
}
/deep/.ant-card-body{
  padding: 24px 45px;
}
.ellipsis {
  width: 184px;
}
</style>